package com.qf.xiaomi.dao.impl;

import com.qf.xiaomi.dao.UserDao;
import com.qf.xiaomi.pojo.User;
import com.qf.xiaomi.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

/**
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
public class UserDaoImpl implements UserDao {
    @Override
    public User findByUsername(String username) {
        QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select * from tb_user where username  = ?";
        try {
            User user = qr.query(sql, new BeanHandler<>(User.class), username);
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("UserDao:根据用户名查询用户失败");
        } finally {
            //释放资源（关闭连接）
        }
        return null;
    }

    @Override
    public void add(User user) {
        QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "INSERT INTO `tb_user` ( `username`, `password`, `email`, `gender`, `flag`, `role`) VALUES ( ?, md5(?), ?, ?, ?, ?)";
        try {
            qr.update(sql, user.getUsername(), user.getPassword(), user.getEmail(), user.getGender(), user.getFlag(), user.getRole());
        } catch (SQLException e) {
            System.out.println("UserDao: 注册失败");
            e.printStackTrace();
        }
    }

    @Override
    public User findUserAndPwd(String username, String password) {
        QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select * from tb_user where username  = ? and password = md5(?)";
        try {
            User user = qr.query(sql, new BeanHandler<>(User.class), username, password);
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("UserDao:根据用户名查询用户失败");
        } finally {
            //释放资源（关闭连接）
        }
        return null;
    }
}
